package top.someapp.dxf2dsvg.dxf;

import javax.annotation.Nonnull;
import java.util.*;

/**
 * @author zwz
 * Created on 2020-04-17
 */
public class SectionBlocks implements Section {
    private Map<String, Block> blockMap = new LinkedHashMap<>();
    private boolean blockStart;
    private boolean blockEnd;
    private Block block;
    private boolean blkRefStart;

    @Override
    public SectionName name() {
        return SectionName.BLOCKS;
    }

    @Override
    public List<Item> items() {
        return null;
    }

    public Collection<Block> getBlocks() {
        return Collections.unmodifiableCollection(blockMap.values());
    }

    private void addBlock(String name) {
        if (!blockMap.containsKey(name)) {
            block = new Block(name);
            blockMap.put(name, block);
        }
    }

    @Override
    public void onItemFound(@Nonnull Item item) {
        if (item.code == 100) {
            if ("AcDbBlockBegin".equals(item.value)) {
                blockStart = true;
                blockEnd = false;
                return;
            } else if ("AcDbBlockReference".equals(item.value)) { // ref other block
                blkRefStart = true;
            } else if ("AcDbBlockEnd".equals(item.value)) {
//                block = null;
                blockEnd = true;
                return;
            }
        }
        if (blockStart && !blockEnd) { // in block
            if (2 == item.code && item.isCodeStartWithPadding()) { // block name
                String name = item.value;
                if (name.startsWith("*")) { // ignore special block, eg: *Model_Space, *Paper_Space
                    blockEnd = true;
                    return;
                }
                if (blkRefStart) {
                    blkRefStart = false;
                    System.out.println("found block ref: " + name);
                    if (block == null) {
                        System.out.println("can not find block ref: " + name);
                    } else {
                        block.setup(item);
                    }
                } else {
                    System.out.println("found block: " + name);
                    addBlock(name);
                }
            } else if (0 == item.code && "ENDBLK".equals(item.value)) {
                blockEnd = true;
            } else {
                if (block != null) {
                    block.setup(item);
                }
//                System.out.println("SKIP " + item);
            }
        }
    }

    @Override
    public String toString() {
        return "SectionBlocks{" +
                "blocks=" + blockMap +
                '}';
    }
}
